<template>
    <div>
        <el-card style="max-width: 100%;margin: 20px;">
            <el-button type="primary" @click="showDialog" v-has="`btn.Trademark.add`">添加品牌</el-button>
            <el-table :data="tableData" border style="width: 100%">
                <el-table-column prop="tmName" label="名称" width="180" />
                <!-- <el-table-column prop="logoUrl" label="图片" width="180" /> -->
                <el-table-column>
                    <template #="scope">
                        <img :src="scope.row.logoUrl" style="width:100px;height: 100px;"></img>
                    </template>
                </el-table-column>
                <el-table-column label="Operations" min-width="120">
                    <template #="scope">
                        <el-button size="small" color="orange" :icon="Edit" @click="updateDialog(scope.row)">
                            <!-- @click="handleClick" -->
                        </el-button>
                        <el-popconfirm
                        confirm-button-text="Yes"
                        cancel-button-text="No"
                        :icon="InfoFilled"
                        icon-color="#626AEF"
                        title="Are you sure to delete this?"
                        @confirm="confirmEvent(scope.row.id)"
                        @cancel="cancelEvent"
                      >
                      <template #reference>
                        <el-button size="small" color="red" :icon="Delete"></el-button>
                        </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[3, 5, 7, 9]"
                :background="true" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>
        <el-dialog v-model="dialogFormVisible" :title="trademarkParams.id?'修改品牌':'添加品牌'" width="500">
            <el-form :model="trademarkParams" style="width: 80%;" ref="ruleFormRef" :rules="rules">
                <!-- label-width属性让左边的标题对齐 -->
                <el-form-item label="品牌名称" label-width="80px" prop="tmName">
                    <el-input v-model="trademarkParams.tmName" autocomplete="off" />
                </el-form-item>
                <el-form-item label="品牌Logo" label-width="80px">
                    <!-- upload组件版性::action图片上传路径书写/api,代理服务器不发送这次post请求 -->
                    <el-upload class="upload-demo" action="/api/admin/product/fileUpload"
                        :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
                        <!-- <el-icon class="el-icon--upload"><upload-filled /></el-icon> -->

                        <img v-if="trademarkParams.logoUrl" :src="trademarkParams.logoUrl"  style="width:100px;height: 100px;" />
                        <!-- <h1>{{trademarkParams.logoUrl}}</h1> -->
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>

</template>

<script setup lang="ts">
    import { Edit, Delete } from '@element-plus/icons-vue'
    import { ElMessage } from 'element-plus'
    //引入组合式API商数ref
    import { ref, onMounted, reactive, nextTick } from 'vue';
    import type { UploadProps } from 'element-plus'
    //当前页码
    let pageNo = ref(1);
    //每一页展示多少条数据
    let limit = ref(3);
    //数据总条数
    let total = ref(0)
    let dialogFormVisible = ref(false)


    const tableData = ref([])
    import { reqHasTrademark, reqDeleteTrademark, reqAddOrUpdateTrademark } from '@/api/product/trademark/index.ts'
    import type { FormInstance, FormRules } from 'element-plus'
    //定义收集新增品牌数据
    let trademarkParams = reactive({
        tmName: "",
        logoUrl: ""
    })
    const ruleFormRef = ref()
    //品牌自定义凌验规则方法
    //无当表单元素触发h1ur时候,会触发此方法console.log(value);
    //自定义校验规则
    const check = (rule: any, value: any, callBack: any) => {
        if (value.trim().length >= 2) {
            callBack();
        } else { callBack(new Error('品牌名称位数大于等于两位')) }
    }
    // 表单校验规则对象
    const rules = reactive({
        tmName: [
            { required: true, trigger: 'blur', validator: check },

        ]
    })
    const submitForm = async () => {
        //如果是失败的话，不会继续往下面执行了，到这里会停止
        await ruleFormRef.value.validate()
        let res = await reqAddOrUpdateTrademark(trademarkParams)
        if (res.code === 200) {
            reqData();
            dialogFormVisible.value = false
            ElMessage({
                type: 'success',
                message: trademarkParams.id?'修改成功':'添加成功',
            })
        }else{
            ElMessage({
                type: 'error',
                message:  trademarkParams.id?'修改失败':'添加失败',
            })
        }
    }
    onMounted(() => {

        reqData();
    })
    const reqData = async () => {
        let res = await reqHasTrademark(pageNo.value, limit.value)
        console.log(res);
        tableData.value = res.data.records
        total.value = res.data.total
    }
    
    const handleSizeChange = () => {
        pageNo.value = 1;
        reqData();
    }
    const handleCurrentChange = () => {
        reqData();
    }


    const handleAvatarSuccess: UploadProps['onSuccess'] = (
        response,
        uploadFile
    ) => {
        //   imageUrl.value = URL.createObjectURL(uploadFile.raw!)
        console.log(response);
        // trademarkParams.logoUrl=
    }
    const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
        if (rawFile.type !== 'image/jpeg') {
            ElMessage.error('Avatar picture must be JPG format!')

            return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
            ElMessage.error('Avatar picture size can not exceed 2MB!')

            return false
        }

        return true
    }
    //展示添加对话框
    const showDialog = () => {

        dialogFormVisible.value = true
        //第一种写法:ts的间号语法formRef.value?.clearvalidate('tmName");/formRef.value?.clearvalidate('logoUrl");
        nextTick(() => {
            ruleFormRef.value.clearValidate('tmName');
        })
        trademarkParams.id = undefined
        trademarkParams.tmName = ''
        trademarkParams.logoUrl = ''
    }
    //修改对话框
    const updateDialog=(row)=>{
        dialogFormVisible.value = true
        //第一种写法:ts的间号语法formRef.value?.clearvalidate('tmName");/formRef.value?.clearvalidate('logoUrl");
        nextTick(() => {
            ruleFormRef.value.clearValidate('tmName');
        })
        //后面的替换前面的
        Object.assign(trademarkParams,row);
        
    }
//删除本行记录
import { InfoFilled } from '@element-plus/icons-vue'

const confirmEvent = async(id) => {
  console.log('confirm!')
  let res=await reqDeleteTrademark(id)
  if(res.code===200){
    ElMessage({
        type:'success',
        message:'删除成功'
    })
    // console.log(tableData.value.length);
    // 这里请求的页码如果是一页的最后一个了，需要直接请求前一页的数据注意
    // tableData.value.length这个指的是当前页数组的的长度
    reqData(tableData.value.length>1?pageNo.value:pageNo.value-1)
  }else{
    ElMessage({
        type:'error',
        message:'删除失败'
    })
  }
}
const cancelEvent = () => {
    ElMessage({
        type:'info',
        message:'取消删除'
    })

}
</script>
<style scoped lang='scss'>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
<style>
    .avatar-uploader .el-upload {
        border: 1px dashed var(--el-border-color);
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: var(--el-transition-duration-fast);
    }

    .avatar-uploader .el-upload:hover {
        border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>